<template>
	<view >
		<ly-tree :tree-data="data"
			:props="defaultProps" 
			ref="tree" 
			node-key="id" 
			show-radio 
			checkOnClickNode
			@node-click="handleNodeClick" 
			@radio-change="handleRadioChange">
		</ly-tree>
		<view class="cu-load load-modal" v-if="isLoading">
			<view class="gray-text">加载中...</view>
		</view>
	</view>
	
</template>


<script>
	import LyTree from '@/components/ly-tree/ly-tree.vue'
	export default {
		components: {
			LyTree
		},
		data() {
			return {
				data: [],
				defaultProps: {
					children: 'children',
					label: 'fullName'
				},
				isLoading: true
			};
		},
		mounted() {				
			this.$minApi.getGoodsWareHouses().then(res => {
				const data = res
				if (data) {
					this.data =	this.getGoodsPosiData(data)
				}
			}).catch(err => {
				console.log(err)
			}).finally(() => {
				this.isLoading = false
			})
		},
		methods: {
			handleRadioChange(obj) {
				this.$emit('selected', obj)
			},
			handleNodeClick(obj) {

			},
			getGoodsPosiData(data) {
				
				var val = [];
				// 将数据存储为 以 id 为 KEY 的 map 索引数据列
				var map = {};
				data.forEach((item) => {
					map[item.id] = item
				})
				data.forEach((item) => {
					// 以当前遍历项，的pid,去map对象中找到索引的id
			
					var parent = map[item.fatherID]
					// 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
					if (parent) {
						(parent.children || ( parent.children = [] )).push(item)
					} else {
						//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
						val.push(item)
					}
				})
				
				return val
					
			}
		}
	};
</script>
